<template>
  <div>
    <div class="card welcome-card" style="padding: 15px; margin-bottom: 10px">
      您好，{{ user?.name }}！欢迎使用报修统计系统
      <el-button type="primary" style="margin-left: 10px" @click="exportStatistics" v-if="user.role === 'ADMIN'">导出统计报表</el-button>
    </div>

    <div style="margin-bottom: 10px" v-if="user.role === 'ADMIN'">
      <el-row :gutter="10">
        <el-col :span="24" :xs="24" :sm="8">
          <el-card>
            <div style="display: flex; align-items: center">
              <div style="width: 150px">
                <div style="font-size: 20px">报修总数</div>
              </div>
              <div style="flex: 1">
                <div style="font-size: 16px; color: red; font-weight: bold">{{ stats.totalRepairs }}</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="24" :xs="24" :sm="8">
          <el-card>
            <div style="display: flex; align-items: center">
              <div style="width: 150px">
                <div style="font-size: 20px">维修成功率</div>
              </div>
              <div style="flex: 1">
                <div style="font-size: 16px; color: green; font-weight: bold">{{ stats.successRate }}%</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="24" :xs="24" :sm="8">
          <el-card>
            <div style="display: flex; align-items: center">
              <div style="width: 150px">
                <div style="font-size: 20px">平均评分</div>
              </div>
              <div style="flex: 1">
                <div style="font-size: 16px; color: orange; font-weight: bold">{{ stats.averageRating }}</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <div style="margin-bottom: 10px" v-if="user.role === 'ADMIN'">
      <el-date-picker value-format="yyyy-MM-dd" format="yyyy-MM-dd" v-model="start" placeholder="请选择开始日期查询" style="width: 100%; margin-right: 10px"></el-date-picker>
      <el-date-picker value-format="yyyy-MM-dd" format="yyyy-MM-dd" v-model="end" placeholder="请选择结束日期查询" style="width: 100%;"></el-date-picker>
      <el-button type="info" plain style="width: 48%; margin-bottom: 10px" @click="fetchStatistics">查询</el-button>
      <el-button type="warning" plain style="width: 48%; margin-bottom: 10px" @click="resetDateRange">重置</el-button>
    </div>

    <div v-if="user.role === 'ADMIN'" :style="{ display: 'flex', 'flex-direction': isDesktop ? 'row' : 'column', 'grid-gap': '10px', 'margin-bottom': '10px' }">
      <div :style="{ width: isDesktop ? '48%' : '100%' }" class="card">
        <div id="repairStatusPie" style="width: 100%; height: 350px"></div>
      </div>
      <div :style="{ width: isDesktop ? '48%' : '100%' }" class="card">
        <div id="ratingBar" style="width: 100%; height: 350px"></div>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts';

export default {
  name: 'RepairStats',
  data() {
    return {
      user: JSON.parse(localStorage.getItem('xm-user') || '{}'),
      start: null,
      end: null,
      stats: {
        totalRepairs: 120,
        successRate: 85,
        averageRating: 4.3,
      },
      repairStatusData: [
        { name: '待分配', value: 20 },
        { name: '维修中', value: 40 },
        { name: '已完成', value: 50 },
        { name: '异常', value: 5 },
        { name: '退回', value: 5 },
      ],
      ratingDistribution: [5, 10, 20, 35, 50],
      isDesktop: window.innerWidth >= 768 // 初始判断
    };
  },
  created() {
    this.fetchStatistics();
    window.addEventListener('resize', this.handleResize); // 监听窗口大小变化
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize); // 移除监听
  },
  methods: {
    handleResize() {
      this.isDesktop = window.innerWidth >= 768; // 更新判断
    },
    fetchStatuses() {
      this.$request.get('/admin/repair/statuses', {
        params: {
          start: this.start,
          end: this.end,
        }
      }).then(res => {
        this.stats = res.data || {};
      });
    },
    fetchRepairStatusData() {
      this.$request.get('/admin/repair/statusPie', {
        params: {
          start: this.start,
          end: this.end,
        }
      }).then(res => {
        this.repairStatusData = res.data || [];
      });
    },
    fetchRatingDistribution() {
      this.$request.get('/admin/repair/ratingDistribution', {
        params: {
          start: this.start,
          end: this.end,
        }
      }).then(res => {
        this.ratingDistribution = res.data || [];
      });
    },
    initCharts() {
      // 初始化维修状态饼图
      const repairStatusOption = {
        title: {
          text: '维修状态统计',
          subtext: '报修单数量',
          left: 'center',
        },
        tooltip: {
          trigger: 'item',
        },
        legend: {
          orient: 'vertical',
          left: 'left',
        },
        series: [
          {
            type: 'pie',
            center: ['50%', '60%'],
            radius: '50%',
            data: this.repairStatusData,
            label: {
              show: true,
              formatter(param) {
                return `${param.name} (${param.percent}%)`;
              },
            },
          },
        ],
      };

      const repairStatusChart = echarts.init(document.getElementById('repairStatusPie'));
      repairStatusChart.setOption(repairStatusOption);

      // 初始化评分分布柱状图
      const ratingBarOption = {
        title: {
          text: '评价评分分布',
          subtext: '评分数量',
          left: 'center',
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow',
          },
        },
        xAxis: {
          type: 'category',
          data: ['1星', '2星', '3星', '4星', '5星'],
        },
        yAxis: {
          type: 'value',
        },
        series: [
          {
            name: '数量',
            type: 'bar',
            data: this.ratingDistribution,
            label: {
              show: true,
              position: 'top',
            },
          },
        ],
      };

      const ratingBarChart = echarts.init(document.getElementById('ratingBar'));
      ratingBarChart.setOption(ratingBarOption);
    },
    fetchStatistics() {
      this.fetchStatuses();
      this.fetchRepairStatusData();
      this.fetchRatingDistribution();
      this.initCharts();
    },
    resetDateRange() {
      this.start = null;
      this.end = null;
      this.fetchStatistics();
    },
    exportStatistics() {
      let url = this.$baseUrl + '/admin/repair/statsExport'
      window.open(url);
    },
  },
};
</script>

<style scoped>
.card {
  padding: 20px;
  border: 1px solid #ebeef5;
  border-radius: 6px;
  background: #fff;
}

.welcome-card {
  text-align: center;
}

@media (max-width: 767px) {
  .welcome-card button {
    display: block;
    margin: 10px auto 0;
  }
}
</style>

